package permission

import (
	"fmt"
	"github.com/casbin/casbin"
	xormadapter "github.com/casbin/xorm-adapter"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
)

func init() {
	a := xormadapter.NewAdapter("mysql", "root:#Hqr214505161@tcp(127.0.0.1:3306)/goblog?charset=utf8", true)
	e := casbin.NewEnforcer("./rbac_models.conf", a)
	err := e.LoadPolicy()
	if err != nil {
		fmt.Println(err)
		return
	}

	router := gin.New()
	router.POST("/api/v1/add", func(context *gin.Context) {
		fmt.Println("增加policy")
		if ok := e.AddPolicy("admin", "/api/v1/hello", "GET"); !ok {
			fmt.Println("Policy已经存在")
		} else {
			fmt.Println("增加成功")
		}
	})
	// 删除policy
	//删除policy
	router.DELETE("/api/v1/delete", func(c *gin.Context) {
		fmt.Println("删除Policy")
		if ok := e.RemovePolicy("admin", "/api/v1/hello", "GET"); !ok {
			fmt.Println("Policy不存在")
		} else {
			fmt.Println("删除成功")
		}
	})
	//获取policy
	router.GET("/api/v1/get", func(c *gin.Context) {
		fmt.Println("查看policy")
		list := e.GetPolicy()
		for _, vlist := range list {
			for _, v := range vlist {
				fmt.Printf("value: %s, ", v)
			}
		}
	})
	router.Use(Authorize(e))
	//创建请求
	router.GET("/api/v1/hello", func(c *gin.Context) {
		fmt.Println("Hello 接收到GET请求..")
	})

	router.Run(":8080") //参数为空 默认监听8080端口
}

func Authorize(e *casbin.Enforcer) gin.HandlerFunc {
	return func(context *gin.Context) {
		obj := context.Request.URL.RequestURI()
		act := context.Request.Method
		sub := "admin"
		fmt.Println(obj)
		if ok := e.Enforce(sub, obj, act); ok {
			fmt.Println("通过验证")
			context.Next()
		} else {
			fmt.Println("验证没有通过")
			context.Abort()
		}
	}
}
